package event

import (
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/models/event"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/clients"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/log"
	"fmt"
)

const (
	EventResourceTypeProcess = "process"
	EventResourceTypeSession = "session"

	EventResourceTraceService = "appgateway"
	EventTraceStateNormal     = "NORMAL"
	EventTraceStateWarning    = "WARNING"
	EventTraceStateIncident   = "INCIDENT"
	EventTypeData             = "data"
	EventTypeManager          = "manager"

	EventSmnMessagePattern = "Have triggerred an event: " +
		"Name: %s; ResourceType: %s; TraceService: %s; TraceState: %s; Details: %s."
)

// 防止循环引用
type ResourceEvent struct {
	ResourceId string
	FleetId    string
}

func RegisterProcessError(eventName string, process ResourceEvent, detail string, state string) {
	smnMessage := fmt.Sprintf(EventSmnMessagePattern, eventName, EventResourceTypeProcess, EventResourceTraceService, state, detail)
	eventReq := &event.RegisterEventRequest{
		Name:         eventName,
		ResourceId:   process.ResourceId,
		ResourceType: EventResourceTypeProcess,
		TraceService: EventResourceTraceService,
		TraceState:   state,
		EventType:    EventTypeData,
		SourceIp:     clients.GetLocalIP(),
		Details:      detail,
		SmnMessage:   smnMessage,
	}
	sg, err := clients.AASSClient.GetScalingGroupDetailsByFleetId(process.FleetId)
	if err != nil {
		log.RunLogger.Errorf("Get scaling group by FleetId %s Error for %v", process.FleetId, err)
		return
	}
	go clients.AASSClient.RegisterEvent(eventReq, sg.ProjectId)
}

func RegisterServerSessionError(eventName string, session ResourceEvent, detail string, state string) {
	smnMessage := fmt.Sprintf(EventSmnMessagePattern, eventName, EventResourceTypeSession, EventResourceTraceService, state, detail)
	eventReq := &event.RegisterEventRequest{
		Name:         eventName,
		ResourceId:   session.ResourceId,
		ResourceType: EventResourceTypeSession,
		TraceService: EventResourceTraceService,
		TraceState:   state,
		EventType:    EventTypeData,
		SourceIp:     clients.GetLocalIP(),
		Details:      detail,
		SmnMessage:   smnMessage,
	}
	sg, err := clients.AASSClient.GetScalingGroupDetailsByFleetId(session.FleetId)
	if err != nil {
		log.RunLogger.Errorf("Get scaling group by FleetId %s Error for %v", session.FleetId, err)
		return
	}
	go clients.AASSClient.RegisterEvent(eventReq, sg.ProjectId)
}
